package com.wycdrive.nyc.main;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BaiduNaviManagerFactory;
import com.baidu.navisdk.adapter.IBNRoutePlanManager;
import com.baidu.navisdk.adapter.IBNTTSManager;
import com.baidu.navisdk.adapter.IBaiduNaviManager;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebConfig;
import com.just.agentweb.PermissionInterceptor;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.bugly.Bugly;
import com.wycdrive.nyc.R;
import com.wycdrive.nyc.beas.BaseActivity;
import com.wycdrive.nyc.model.api.ApiManager;
import com.wycdrive.nyc.model.vo.NaviAddress;
import com.wycdrive.nyc.model.vo.ResultData;
import com.wycdrive.nyc.navi.sdkdemo.NormalUtils;
import com.wycdrive.nyc.navi.sdkdemo.newif.DemoGuideActivity;
import com.wycdrive.nyc.util.FileAndSharedPreferenceUtil;
import com.wycdrive.nyc.util.LocationRecordListener;
import com.wycdrive.nyc.util.LocationRecordUtil;
import com.wycdrive.nyc.util.LocationUtil;
import com.wycdrive.nyc.util.RetryWithDelay;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BooleanSupplier;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    protected PermissionInterceptor mPermissionInterceptor = new PermissionInterceptor() {

        @Override
        public boolean intercept(String url, String[] permissions, String action) {
            Log.i("ffffffffffff", "url:" + url + "  permission:" + permissions + " action:" + action);
            return false;
        }
    };

    //app.linkgogo.cn
    public static final String MAIN_URL = "http://app.linkgogo.cn/Home/LoginDriver/whiteIndex";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    public static final String NAVI_STATUS = "navi_status";
    private AgentWeb mAgentWeb;
    private Button button, button1;
    private boolean hasInitSuccess = false;
    private BNRoutePlanNode mStartNode = null;
    private String mSDCardPath = null;
    private static final String APP_FOLDER_NAME = "DriveDiDi";
    private static final int REQUEST_CODE_PERMISSION_MULTI = 101;
    private List<String> deniedPermissions;
    private static final int REQUEST_CODE_MULTI = 200;
    private Disposable subscription;
    private boolean isOrdering = false;
    private LocationRecordUtil locationRecordUtil;
    private ObservableEmitter<Integer> startNaviEmitter;
    public static int type;
    public static String oid;
    private boolean isPressTwice = false;


    @Override
    public void onBackPressed() {
        if (mAgentWeb == null) {
            finish();
        }
        callJSFunction("canGoBack()", new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String value) {
                Log.d("ffffff", "onReceiveValue:fffffff  canGoBack" + value);
                if ("false".equals(value)) {
                    return;
                }
                if (isHomePage()) {
                    promptExit();
                    return;
                }
                if (!mAgentWeb.back()) {
                    promptExit();
                }
            }
        });
    }

    private void promptExit() {
        if (isPressTwice == true) {
            finish();
            return;
        }
        isPressTwice = true;
        Toast.makeText(this, "再次点击返回键退出", Toast.LENGTH_SHORT).show();
        Observable.just(true).delay(2, TimeUnit.SECONDS).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                isPressTwice = false;
            }
        });
    }

    private boolean isHomePage() {
        if (mAgentWeb == null || mAgentWeb.getWebCreator() == null || mAgentWeb.getWebCreator().getWebView() == null || mAgentWeb.getWebCreator().getWebView().getUrl() == null) {
            return true;
        }
        return mAgentWeb.getWebCreator().getWebView().getUrl().startsWith("http://app.linkgogo.cn/Home/Listens/") || mAgentWeb.getWebCreator().getWebView().getUrl().startsWith("http://app.linkgogo.cn/Home/LoginDriver/index") || mAgentWeb.getWebCreator().getWebView().getUrl().startsWith(MAIN_URL);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initView() {
        Bugly.init(getApplicationContext(), "eaa1a25250", false);
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEachCombined(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> { // will emit 1 Permission object
                    if (permission.granted) {
                        // All permissions are granted !
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // At least one denied permission without ask never again

                    } else {
                        // At least one denied permission with ask never again
                        // Need to go to the settings
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("提示")
                                .setMessage("我们需要的一些必要权限被禁止，请授权给我们。")
                                .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //引导用户至设置页手动授权
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", getApplicationContext().getPackageName(), null);
                                        intent.setData(uri);
                                        startActivity(intent);
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //引导用户手动授权，权限请求失败
                                    }
                                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                //引导用户手动授权，权限请求失败
                                finish();
                            }
                        }).show();
                    }

                });
        initStartNaviObservable();
        init();
        new LocationUtil(this).start();
        if (initDirs()) {
            initNavi();
        }
        //checkNaviUnormalExit();
        locationRecordUtil = new

                LocationRecordUtil(this, new LocationRecordListener() {
            @Override
            public void onStartRecord() {

            }

            @Override
            public void onStopRecord() {
            }

            @Override
            public void onDestory() {
            }
        });
    }


    @Override
    protected void initData() {

    }

    private WebViewClient mWebViewClient = new WebViewClient() {


        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            AgentWebConfig.syncCookie(MAIN_URL, FileAndSharedPreferenceUtil.readCookie(MainActivity.this));
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        }
    };


    private void init() {
        mAgentWeb = AgentWeb.with(this)
                //传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                .setAgentWebParent((LinearLayout) findViewById(R.id.root), new LinearLayout.LayoutParams(-1, -1))
                .closeIndicator()
                .setWebChromeClient(mWebChromeClient)
                //.setAgentWebWebSettings(new CustomSettings())
                .setWebViewClient(mWebViewClient)
                .setPermissionInterceptor(mPermissionInterceptor)
                .createAgentWeb()
                .ready().go(MAIN_URL);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            mAgentWeb.getWebCreator().getWebView().getSettings().setMediaPlaybackRequiresUserGesture(false);
        }
        button = findViewById(R.id.btn);
        button1 = findViewById(R.id.btn1);
        button1.setOnClickListener(this);
        button.setOnClickListener(this);
        regAndroidMethod();

    }

    private void callJSFunction(String methodName, ValueCallback<String> callback) {
        WebView wv = mAgentWeb.getWebCreator().getWebView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//sdk>19才有用
            wv.evaluateJavascript(methodName, callback);
        } else {
            wv.loadUrl("javascript:" + methodName);
        }
    }


//    private void callJSFunction(String methodName, String... params) {
//        mAgentWeb.getJsAccessEntrace().quickCallJs("", params);
//    }

    private void regAndroidMethod() {
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new AndroidInterface(mAgentWeb, this));
        //window.android.callAndroid(); js call
    }

    @Override
    protected void onPause() {
        Log.d("fffff", "onPause: " + getCookie());
        FileAndSharedPreferenceUtil.keepCookie(MainActivity.this, getCookie());
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        locationRecordUtil.onDestory();
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn:
                sendLocation("/xx");
//                locationRecordUtil.setEndLat(118.1634032034984900);
//                locationRecordUtil.setEndLon(39.6316359368307540);
//                locationRecordUtil.startRecord();
                break;
            case R.id.btn1:
//                locationRecordUtil.stopRecord();
                break;
        }

    }

    public class AndroidInterface {
        public AndroidInterface(AgentWeb mAgentWeb, MainActivity mainActivity) {
            //保留
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void startOrdering(String path) {
            if (path == null || path.equals("")) {
                return;
            }
            sendLocation(path);
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void stopOrdering() {
            stopSendLocation();
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void joinNavigation(int type, String oid) {
            MainActivity.type = type;
            MainActivity.oid = oid;
            //点击导航
            startNavi(1);
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void startNavigation(int type, String oid) {
            MainActivity.type = type;
            MainActivity.oid = oid;
            startNavi(2);
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void stopNavigation() {
            stopNavi();
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void setCanGoBack(boolean isCanGoback) {
            if (!isCanGoback) {
                return;
            }
            if (isHomePage()) {
                promptExit();
                return;
            }
            if (!mAgentWeb.back()) {
                promptExit();
            }
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void startRecordLocation(double lat, double lon, int type, String oid) {
            MainActivity.type = type;
            MainActivity.oid = oid;
            locationRecordUtil.setEndLat(lat);
            locationRecordUtil.setEndLon(lon);
            locationRecordUtil.startRecord();
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void stopRecordLocation() {
            locationRecordUtil.stopRecord();
        }

        @JavascriptInterface //注意，所有可被JS调用的函数，一定要加上@JavascriptInterface，否则JS无法调用
        public void getVersion() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callJSFunction("onReceiveAppVersion(" + getAppVersion() + ")", new ValueCallback<String>() {
                        @Override
                        public void onReceiveValue(String value) {

                        }
                    });
                }
            });

        }

    }

    /**
     * 获取应用的版本号
     *
     * @return 应用版本号
     */
    private int getAppVersion() {
        Context context = this;
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }

    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }


    private void routeplanToNavi(final int coType, double lngStart, double latStart, String nameStart, String descriptionStart,
                                 double lngEnd, double latEnd, String nameEnd, String descriptionEnd) {
        if (!hasInitSuccess) {
            Toast.makeText(MainActivity.this, "还未初始化!", Toast.LENGTH_SHORT).show();
        }

//        BNRoutePlanNode sNode = new BNRoutePlanNode(121.598568, 38.893388, "乐嘉服务公寓", "星海广场", coType);
//        BNRoutePlanNode eNode = new BNRoutePlanNode(116.39750, 39.90882, "北京天安门", "北京天安门", coType);
        BNRoutePlanNode sNode = null;
        BNRoutePlanNode eNode = null;
        switch (coType) {
            case BNRoutePlanNode.CoordinateType.BD09LL: {
                sNode = new BNRoutePlanNode(lngStart, latStart, nameStart, descriptionStart, coType);
                eNode = new BNRoutePlanNode(lngEnd, latEnd, nameEnd, descriptionEnd, coType);
                break;
            }
            default:
                break;
        }

        mStartNode = sNode;

        List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
        list.add(sNode);
        list.add(eNode);

        BaiduNaviManagerFactory.getRoutePlanManager().routeplanToNavi(
                list,
                IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DEFAULT,
                null,
                new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START:
                                Toast.makeText(MainActivity.this, "算路开始", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS:
                                Toast.makeText(MainActivity.this, "算路成功", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED:
                                Toast.makeText(MainActivity.this, "算路失败", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI:
                                Toast.makeText(MainActivity.this, "算路成功准备进入导航", Toast.LENGTH_SHORT)
                                        .show();
                                Intent intent = new Intent(MainActivity.this,
                                        DemoGuideActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable(ROUTE_PLAN_NODE, mStartNode);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                break;
                            default:
                                // nothing
                                break;
                        }
                    }
                });
    }

    //初始化BaiduNaviManager
    private void initNavi() {

        BaiduNaviManagerFactory
                .getBaiduNaviManager()
                .init(this,
                        mSDCardPath, APP_FOLDER_NAME, new IBaiduNaviManager.INaviInitListener() {

                            @Override
                            public void onAuthResult(int status, String msg) {
                                String result;
                                if (0 == status) {
                                    result = "key校验成功!";
                                } else {
                                    result = "key校验失败, " + msg;
                                }
                                //Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                            }

                            @Override
                            public void initStart() {
                                Toast.makeText(MainActivity.this, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void initSuccess() {
                                Toast.makeText(MainActivity.this, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                                hasInitSuccess = true;
                                // 初始化tts
                                initTTS();
                            }

                            @Override
                            public void initFailed() {
                                Toast.makeText(MainActivity.this, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
                            }
                        });
    }

    private void initTTS() {
        // 使用内置TTS
        BaiduNaviManagerFactory.getTTSManager().initTTS(getApplicationContext(),
                getSdcardDir(), APP_FOLDER_NAME, NormalUtils.getTTSAppID());

        // 不使用内置TTS
        //BaiduNaviManagerFactory.getTTSManager().initTTS(mTTSCallback);

        // 注册同步内置tts状态回调
        BaiduNaviManagerFactory.getTTSManager().setOnTTSStateChangedListener(
                new IBNTTSManager.IOnTTSPlayStateChangedListener() {
                    @Override
                    public void onPlayStart() {
                        Log.e("BNSDKDemo", "ttsCallback.onPlayStart");
                    }

                    @Override
                    public void onPlayEnd(String speechId) {
                        Log.e("BNSDKDemo", "ttsCallback.onPlayEnd");
                    }

                    @Override
                    public void onPlayError(int code, String message) {
                        Log.e("BNSDKDemo", "ttsCallback.onPlayError");
                        Log.e("BNSDKDemo", "ttsCallback.onPlayError  " + message);
                    }
                }
        );

        // 注册内置tts 异步状态消息
        BaiduNaviManagerFactory.getTTSManager().setOnTTSStateChangedHandler(
                new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        Log.e("BNSDKDemo", "ttsHandler.msg.what=" + msg.what);
                    }
                }
        );
    }


    private void sendLocation(final String path) {
        if (isOrdering) {
            return;
        }
        Log.d("ffffffff", "开始接单");
        isOrdering = true;
        Observable.interval(0, 5, TimeUnit.SECONDS).filter(new Predicate<Long>() {
            @Override
            public boolean test(Long aLong) throws Exception {
                return LocationUtil.lat != -10000;
            }
        }).flatMap(new Function<Long, ObservableSource<ResultData>>() {
            @Override
            public ObservableSource<ResultData> apply(Long aLong) throws Exception {
                return ApiManager.getInstance().getDataService(getCookie()).sendLocation(path, LocationUtil.lon, LocationUtil.lat, type, oid);
            }
        }).retryWhen(new RetryWithDelay(1000, 5000)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Observer<ResultData>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        subscription = d;
                    }

                    @Override
                    public void onNext(ResultData o) {
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("ffffff", "onError: 出现异常");
                        isOrdering = false;
                    }

                    @Override
                    public void onComplete() {
                        isOrdering = false;
                    }
                });

    }

    private void stopSendLocation() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
            isOrdering = false;
            Log.d("ffffffff", "停止接单");
        }
    }

    public static String getCookie() {
        return AgentWebConfig.getCookiesByUrl(MAIN_URL);
    }


    private void startNavi(final int code) {
        final RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .requestEachCombined(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> { // will emit 1 Permission object
                    if (permission.granted) {
                        // All permissions are granted !
                        if (isOpenGPS()) {
                            if (startNaviEmitter != null) {
                                startNaviEmitter.onNext(code);
                            }
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // At least one denied permission without ask never again

                    } else {
                        // At least one denied permission with ask never again
                        // Need to go to the settings
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("提示")
                                .setMessage("我们需要的一些必要权限被禁止，请授权给我们。")
                                .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //引导用户至设置页手动授权
                                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", getApplicationContext().getPackageName(), null);
                                        intent.setData(uri);
                                        startActivity(intent);
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        //引导用户手动授权，权限请求失败
                                    }
                                }).setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                            }
                        }).show();
                    }

                });


    }

    private void initStartNaviObservable() {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                startNaviEmitter = emitter;
            }
        }).throttleFirst(5, TimeUnit.SECONDS).subscribe(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) throws Exception {
                getNaviAddress(integer);
            }
        });
    }

    private void stopNavi() {

    }

    private void getNaviAddress(final int code) {
        ApiManager.getInstance().getDataService(getCookie()).getNaviAddress(type, oid).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).
                subscribe(new Observer<NaviAddress>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(NaviAddress o) {
                        routeplanToNavi4Rxjava(code, o);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void routeplanToNavi4Rxjava(final int code, final NaviAddress naviAddress) {
        if (!hasInitSuccess || LocationUtil.lat == -10000) {
            return;
        }
        NaviAddress.DataBean.SNodeBean sbean = naviAddress.getData().getSNode();
        NaviAddress.DataBean.ENodeBean ebean = naviAddress.getData().getENode();
        final BNRoutePlanNode sNode;
        final BNRoutePlanNode eNode;
        if (code == 1) {
            sNode = new BNRoutePlanNode(LocationUtil.lon, LocationUtil.lat, LocationUtil.name, LocationUtil.description, BNRoutePlanNode.CoordinateType.BD09LL);
            eNode = new BNRoutePlanNode(sbean.getLongitude(), sbean.getLatitude(), sbean.getName(), sbean.getDescription(), BNRoutePlanNode.CoordinateType.BD09LL);
        } else {
            sNode = new BNRoutePlanNode(LocationUtil.lon, LocationUtil.lat, sbean.getName(), sbean.getDescription(), BNRoutePlanNode.CoordinateType.BD09LL);
            eNode = new BNRoutePlanNode(ebean.getLongitude(), ebean.getLatitude(), ebean.getName(), ebean.getDescription(), BNRoutePlanNode.CoordinateType.BD09LL);
        }
        List<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
        list.add(sNode);
        list.add(eNode);

        BaiduNaviManagerFactory.getRoutePlanManager().routeplanToNavi(
                list,
                IBNRoutePlanManager.RoutePlanPreference.ROUTE_PLAN_PREFERENCE_DISTANCE_FIRST,
                null,
                new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_START:
                                Toast.makeText(MainActivity.this, "算路开始", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_SUCCESS:
                                Toast.makeText(MainActivity.this, "算路成功", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_FAILED:
                                Toast.makeText(MainActivity.this, "算路失败", Toast.LENGTH_SHORT)
                                        .show();
                                break;
                            case IBNRoutePlanManager.MSG_NAVI_ROUTE_PLAN_TO_NAVI:
                                Toast.makeText(MainActivity.this, "算路成功准备进入导航", Toast.LENGTH_SHORT)
                                        .show();
                                //记录导航状态
                                FileAndSharedPreferenceUtil.keepCurrentNaviStatus(MainActivity.this, code);                  //记录导航地址
                                FileAndSharedPreferenceUtil.writeNaviAddress(MainActivity.this, naviAddress);
                                Intent intent = new Intent(MainActivity.this,
                                        DemoGuideActivity.class);
                                Bundle bundle = new Bundle();
                                //bundle.putSerializable(ROUTE_PLAN_NODE, eNode);
                                //传递过去
                                bundle.putInt(NAVI_STATUS, code);
                                intent.putExtras(bundle);
                                startActivity(intent);
                                break;
                            default:
                                // nothing
                                break;
                        }
                    }
                });
    }

    /**
     * 检测是否存在异常退出
     */
    private void checkNaviUnormalExit() {
        final int status = FileAndSharedPreferenceUtil.getCurrentNaviStatus(MainActivity.this);
        final NaviAddress address = FileAndSharedPreferenceUtil.readNaviAddress(MainActivity.this);
        Log.d("fffff", "onComplete: " + "回复导航开始");
        if (status != 0 && address != null) {
            //每5秒检测一次当前坐标是否正常,如果正常 重新进入导航
            Observable o = Observable.just(1).delay(5, TimeUnit.SECONDS).retryUntil(new BooleanSupplier() {
                @Override
                public boolean getAsBoolean() throws Exception {
                    return LocationUtil.lat != -10000;
                }
            });
            o.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Integer>() {
                @Override
                public void onSubscribe(Disposable d) {

                }

                @Override
                public void onNext(Integer i) {
                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onComplete() {
                    Log.d("fffff", "onComplete: " + "回复导航成功");
                    routeplanToNavi4Rxjava(status, address);
                }
            });
        }
    }

    private int GPS_REQUEST_CODE = 10;

    /**
     * 检测GPS是否打开
     *
     * @return
     */
    private boolean checkGPSIsOpen() {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    /**
     * 跳转GPS设置
     */
    private boolean isOpenGPS() {
        if (checkGPSIsOpen()) {
            return true;
        } else {
            //没有打开则弹出对话框
            new AlertDialog.Builder(this)
                    .setTitle("请开启GPS")
                    .setMessage("请开启GPS进入行程.")
                    // 拒绝, 退出应用
                    .setNegativeButton("不了",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            })

                    .setPositiveButton("好的",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    //跳转GPS设置界面
                                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                    startActivityForResult(intent, GPS_REQUEST_CODE);
                                }
                            })

                    .setCancelable(false)
                    .show();
            return false;
        }
    }


}
